package com.psm.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;
import org.xvolks.jnative.pointers.Pointer;
import org.xvolks.jnative.pointers.memory.MemoryBlockFactory;

/**
 * 
 * @author 广州朴石茗文化发展有限公司 @Email pushiming@sina.cn
 * Aug 11, 2015 
 * TODO
 */
public class ReadCard {
	
	private static int intport = 1001;
	String strTmp = "";
    int len = 0;
    int ret = 0;  
	/**
	 * 初始化设备
	 * @param Port
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 * @throws UnsupportedEncodingException
	 */
    public  int CVR_InitComm(int Port) throws NativeException, IllegalAccessException, UnsupportedEncodingException 
    {          
          JNative n = null;
          try 
          {
             n = new JNative("Termb.dll", "CVR_InitComm");              
             n.setRetVal(Type.INT); // 指定返回参数的类型
             n.setParameter(0, Port);                   
             n.invoke(); // 调用方法
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
	/**
	 * 关闭串口
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 */
	public  int CVR_CloseComm() throws NativeException,IllegalAccessException 
    {
          JNative n = null;
          try 
          {
             n = new JNative("Termb.dll", "CVR_CloseComm"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型                               
             n.invoke(); // 调用方法
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
      }
	/**
	 * 卡认证
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 */
	public  int CVR_Authenticate() throws NativeException, IllegalAccessException 
    {
          JNative n = null;
          try 
          {
             n = new JNative("Termb.dll", "CVR_Authenticate"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型                              
             n.invoke(); // 调用方法
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
	/**
	 * 读取卡内信息
	 * @param Active
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 */
	public  int CVR_Read_Content(int Active) throws NativeException, IllegalAccessException 
    {
          JNative n = null;
          try 
          {
             n = new JNative("Termb.dll", "CVR_Read_Content"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型
             n.setParameter(0, Active);                   
             n.invoke(); // 调用方法
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
	/**
	 * 链接读卡器
	 * @return
	 */
	public int OpenPort(){
		int ret = 0;
		try {
			ret = CVR_InitComm(intport);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return ret;
	}
	/**
	 * 读取身份证号码
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 */
	public  int GetPeopleIDCode() throws NativeException, IllegalAccessException 
    {
          JNative n = null;           
          try 
          {
             n = new JNative("Termb.dll", "GetPeopleIDCode"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型 
             Pointer a = new Pointer(MemoryBlockFactory.createMemoryBlock(4*10));
             Pointer b = new Pointer(MemoryBlockFactory.createMemoryBlock(4*30));
             n.setParameter(0,b);
             n.setParameter(1,a);              
             n.invoke(); 
             byte[] by = new byte[120];             
             by = b.getMemory();
            try 
            {
                strTmp = new String(by,"gb2312");
            } 
            catch (Exception ex) 
            {
                ex.printStackTrace();
            }

             len = a.getAsInt(0);
             
             a.dispose();
             b.dispose();
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
	
	public  String GetIDCode() throws NativeException, IllegalAccessException 
    {
          JNative n = null;           
          try 
          {
             n = new JNative("Termb.dll", "GetPeopleIDCode"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型 
             Pointer a = new Pointer(MemoryBlockFactory.createMemoryBlock(4*10));
             Pointer b = new Pointer(MemoryBlockFactory.createMemoryBlock(4*30));
             n.setParameter(0,b);
             n.setParameter(1,a);              
             n.invoke(); 
             byte[] by = new byte[120];             
             by = b.getMemory();
            try 
            {
                strTmp = new String(by,"gb2312");
            } 
            catch (Exception ex) 
            {
                ex.printStackTrace();
            }

             len = a.getAsInt(0);
             
             a.dispose();
             b.dispose();
             return strTmp;
          } 
          finally 
          {
             
          }
     }
	/**
	 * 姓名
	 * @return
	 * @throws NativeException
	 * @throws IllegalAccessException
	 */
	public  int GetPeopleName() throws NativeException, IllegalAccessException 
    {
          JNative n = null;           
          try 
          {
             n = new JNative("Termb.dll", "GetPeopleName"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型 
             Pointer a = new Pointer(MemoryBlockFactory.createMemoryBlock(4*10));
             Pointer b = new Pointer(MemoryBlockFactory.createMemoryBlock(4*30));             
             n.setParameter(0,b);
             n.setParameter(1,a);              
             n.invoke(); 
             byte[] by = new byte[120];             
             by = b.getMemory();
            try 
            {
                strTmp = new String(by,"gb2312");
            } 
            catch (UnsupportedEncodingException ex) 
            {
            }

            byte[] bt = new byte[40];  
            bt = a.getMemory();
             len = a.getAsInt(0);
             a.dispose();
             b.dispose();
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
     /**
      * 地址
      * @return
      * @throws NativeException
      * @throws IllegalAccessException
      */
	public  int GetPeopleAddress() throws NativeException, IllegalAccessException 
     {
          JNative n = null;           
          try 
          {
             n = new JNative("Termb.dll", "GetPeopleAddress"); 
             n.setRetVal(Type.INT); // 指定返回参数的类型 
             Pointer a = new Pointer(MemoryBlockFactory.createMemoryBlock(4*10));
             Pointer b = new Pointer(MemoryBlockFactory.createMemoryBlock(4*30));
             n.setParameter(0,b);
             n.setParameter(1,a);              
             n.invoke(); 
             byte[] by = new byte[120];             
             by = b.getMemory();
            try 
            {
                strTmp = new String(by,"gb2312");
            } 
            catch (UnsupportedEncodingException ex) 
            {
            }

             len = a.getAsInt(0);
             
             a.dispose();
             b.dispose();
             return Integer.parseInt(n.getRetVal());
          } 
          finally 
          {
             
          }
     }
      
      /**
       * 以行为单位读取文件，常用于读面向行的格式化文件
       */
      public static List<String> readFileByLines(String fileName) {
          File file = new File(fileName);
          BufferedReader reader = null;
          List<String> info = new ArrayList<String>();
          try {
              System.out.println("读取每行数据：");
              reader = new BufferedReader(new FileReader(file));
              String tempString = null;
              int line = 1;
              // 一次读入一行，直到读入null为文件结束
              while ((tempString = reader.readLine()) != null) {
                  // 显示行号
                  System.out.println("line " + line + ": " + tempString);
                  info.add(tempString);
                  line++;
              }
              reader.close();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              if (reader != null) {
                  try {
                      reader.close();
                  } catch (IOException e1) {
                  }
              }
              return info;
          }
      }
      public void renameFile(String path,String oldname,String newname){ 
          if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
              File oldfile=new File(path+"/"+oldname); 
              File newfile=new File(path+"/"+newname); 
              if(!oldfile.exists()){
                  return;//重命名文件不存在
              }
              if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同，则不允许重命名 
                  System.out.println(newname+"已经存在！"); 
              else{ 
                  oldfile.renameTo(newfile); 
              } 
          }else{
              System.out.println("新文件名和旧文件名相同...");
          }
      }
      
      public CardInfo rd(){
      	CardInfo info = new CardInfo();
  		try {
  			int result = CVR_InitComm(1001);
  			System.out.println("=============="+result);
  			if(result==1){
  				result=CVR_Authenticate();
  				System.out.println("==============a"+result);
  				if(result==1){
  					result=CVR_Read_Content(4);  
  					if(result==1){
  						String code = GetIDCode(); 
  						renameFile(System.getProperty("user.dir"), "wz.txt", code.trim()+".txt");
  						List<String> infolist = readFileByLines(System.getProperty("user.dir")+"\\"+code.trim()+".txt");
//  						System.out.println(infolist.get(0));
  						info.setName(infolist.get(0));
  						info.setSex(infolist.get(1));
  						info.setBir(infolist.get(3));
  						info.setAddress(infolist.get(4));
  						info.setIdnum(infolist.get(5));
  						info.setIdaddress(infolist.get(6));
  						info.setTruedate(infolist.get(7));
  						info.setMz(infolist.get(2));
  					}
  				}
  			}
  		}catch (Exception e) {
  			e.printStackTrace();
  		} 
  		return info;
      }
      
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ReadCard rc = new ReadCard();
		try {
			int result = rc.CVR_InitComm(intport);
			System.out.println("=============="+result);
			if(result==1){
				result=rc.CVR_Authenticate();
				System.out.println("==============a"+result);
				if(result==1){
					result=rc.CVR_Read_Content(4);  
					if(result==1){
						String code = rc.GetIDCode();
						String p = System.getProperty("user.dir")+"/wz.txt";
						rc.renameFile(System.getProperty("user.dir"), "wz.txt", code.trim()+".txt");
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

}
